package com.redis1.zhujie;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;

/**
 * @author: LI-CI-GAO
 * 作者: licigao
 * 日期: 2021/8/27  19:27
 * 描述:
 */
@Aspect
@Component
public class MiDengXingAop {


    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Pointcut("execution(public * com.redis1.web.*.*(..))")
    public void pointcut(){}




    @Around("pointcut() && @annotation(com.redis1.zhujie.MiDengXing)")
    public Object tongzhi(ProceedingJoinPoint joinPoint) throws Throwable {

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();

        HttpServletRequest request = requestAttributes.getRequest();
        String key = request.getParameter("key");

        String lur="if redis.call('get',KEYS[1]) == ARGV[1] then redis.call('del',KEYS[1]) return 1 else return 0 end";

        DefaultRedisScript<Long> defaultRedisScript = new DefaultRedisScript<>();
        defaultRedisScript.setScriptText(lur);
        defaultRedisScript.setResultType(Long.class);

        Long execute = redisTemplate.execute(defaultRedisScript, Collections.singletonList(key), key);

        if(execute==1){
            return joinPoint.proceed();
        }else{
            HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
            response.setCharacterEncoding("utf-8");
            response.getWriter().print("请刷新界面重新提交!");
            return null;
        }


    }

}
